<?php
/**
 * 数据库操作类
 * 
 */
class DB {

 private $resource;
 private $result;

 function __construct($db = "agriculture", $url = "localhost", $name = "agriculture", $pwd = "tom") {
  $conn = mysql_connect($url, $name, $pwd) or die("连接失败");
  mysql_select_db($db, $conn);
  mysql_query("SET NAMES 'utf8'", $conn);
  $this->resource = $conn;
 }

 function insert($table, $values) {
  $sql = "INSERT INTO {$table}";
  $keysql = '';
  $valuesql = '';
  foreach ($values as $key => $value) {
   $keysql .= "{$key},";
   $valuesql .= "'{$value}',";
  }
  $sql = $sql . '(' . substr($keysql, 0, -1) . ')VALUES(' . substr($valuesql, 0, -1) . ')';
  return $this->query($sql);
 }

 function delete($table, $where = '') {
  $sql = "DELETE FROM {$table}";
  if ($where != '')
  $sql .= " WHERE {$where}";
  return $this->query($sql);
 }

 function update($table, $values, $where) {
  $sql = "UPDATE {$table} SET ";
  $keysql = '';
  $valuesql = '';
  foreach ($values as $k => $v) {
   if (ereg("^[0-9]+$", $v)) {
    $sql .= "$k={$v},";
   } else {
    $sql .= "$k='{$v}',";
   }
  }
  $sql = substr($sql, 0, -1);
  $sql .= " WHERE {$where}";
  return $this->query($sql);
 }

 function select($what, $table, $where = '', $orderby = '', $limit = '') {
  $sql = "SELECT {$what} FROM {$table}";
  if ($where != '')
  $sql .= " WHERE {$where}";
  if ($orderby != '')
  $sql .= " ORDER BY {$orderby}";
  if ($limit != '')
  $sql .= " LIMIT {$limit}";
  return $this->fetch_array($this->query($sql));
 }

 function query($sql) {
  return $this->result = mysql_query($sql, $this->resource);
 }

 function fetch_array() {
  $data = array();
  while ($row = mysql_fetch_array($this->result)) {
   array_push($data, $row);
  }
  $this->close();
  return $data;
 }

 function close() {
  mysql_free_result($this->result);
  mysql_close($this->resource);
 }

}

?>